package com.jb.repair.fragment;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.util.AbDialogUtil;
import com.ab.util.AbStrUtil;
import com.ab.view.wheel.AbNumericWheelAdapter;
import com.ab.view.wheel.AbWheelView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jb.repair.F1Application;
import com.jb.repair.R;
import com.jb.repair.acticity.AboutActivity;
import com.jb.repair.acticity.MainActivity;
import com.jb.repair.common.AppConfig;
import com.jb.repair.common.Constants;
import com.jb.repair.common.DialogCallBack;
import com.jb.repair.common.RingAlarm;
import com.jb.repair.dao.LocalDbDao;
import com.jb.repair.model.APKModel;
import com.jb.repair.model.User4Json;
import com.jb.repair.net.HttpClient;
import com.jb.repair.net.HttpCookies;
import com.jb.repair.util.MessageUtil;
import com.jb.repair.util.NetUtil;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class SettingFragment extends Fragment implements View.OnClickListener, DialogCallBack {

    NotifyParentActivity callback = null;
    private TextView tv_time, tvClean, tvAbout, tv_update;
    private final String TAG = "SettingFragment";
    private APKModel apkModel;
    private Gson gson;
    private long currentFileSize = 0L;
    private int persent = 0;
    private TextView timeTextView3 = null;
    private View mTimeView3 = null;
    private boolean dialogShowing = false;
    private Calendar c = Calendar.getInstance();
    private Switch swMeasure;
    SharedPreferences sp;


    public SettingFragment() {

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        callback = (MainActivity) activity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        sp = getActivity().getSharedPreferences(Constants.SP_NAME, getActivity().MODE_PRIVATE);

        View view = inflater.inflate(R.layout.fragment_setting, null);
        mTimeView3 = inflater.inflate(R.layout.choose_two, null);
        initView(view);
        initWheelTime2(mTimeView3, timeTextView3);
        tv_time.setOnClickListener(this);
        tvClean.setOnClickListener(this);
        tvAbout.setOnClickListener(this);
        tv_update.setOnClickListener(this);
        timeTextView3.setOnClickListener(this);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private void initView(View view) {
        timeTextView3 = (TextView) view.findViewById(R.id.measureTimeText3);
        tv_time = (TextView) view.findViewById(R.id.tv_time);
        tvClean = (TextView) view.findViewById(R.id.tv_clean);
        tvAbout = (TextView) view.findViewById(R.id.tv_about);
        tv_update = (TextView) view.findViewById(R.id.tv_update);
        swMeasure = (Switch) view.findViewById(R.id.sw_measure);
        swMeasure.setChecked(sp.getBoolean(Constants.SWITCH_MEASURE, false));
        swMeasure.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    //保存到本地
                    sp.edit().putBoolean(Constants.SWITCH_MEASURE, b).commit();
                    Toast.makeText(getActivity(), "已开启测温测振", Toast.LENGTH_SHORT).show();

                } else {
                    //保存到本地
                    sp.edit().putBoolean(Constants.SWITCH_MEASURE, b).commit();
                    Toast.makeText(getActivity(), "已关闭测温测振", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    @Override
    public void onResult(int requsetViewId, Bundle bundle) {
        switch (requsetViewId) {
            case 0:  //下载更新
                if (bundle.getBoolean("data", false)) {
                    Log.i(TAG, "开始下载APK");
                    MessageUtil.showProgressDialog(getActivity(), "正在下载");
                    new DownLoadFile().execute(apkModel.down_url);
                }
                break;
            case 1:
                String userName = bundle.getString("userName");
                new LoginTask().execute(userName, bundle.getString("pwd"));
                break;
        }
    }

    public void initWheelTime2(View mTimeView, TextView mText) {
        final AbWheelView mWheelViewMM = (AbWheelView) mTimeView.findViewById(R.id.wheelView1);
        final AbWheelView mWheelViewHH = (AbWheelView) mTimeView.findViewById(R.id.wheelView2);
        Button okBtn = (Button) mTimeView.findViewById(R.id.okBtn);
        Button cancelBtn = (Button) mTimeView.findViewById(R.id.cancelBtn);
        mWheelViewMM.setCenterSelectDrawable(this.getResources().getDrawable(R.drawable.wheel_select));
        mWheelViewHH.setCenterSelectDrawable(this.getResources().getDrawable(R.drawable.wheel_select));
        initWheelTimePicker2(getActivity(), mText, mWheelViewMM, mWheelViewHH, okBtn, cancelBtn, 1, 1, true);
    }

    private void initWheelTimePicker2(final Context activity, final TextView mText, final AbWheelView mWheelViewHH, final AbWheelView mWheelViewMM, Button okBtn, Button cancelBtn, int defaultHour, int defaultMinute, boolean initStart) {
        c.setTimeInMillis(System.currentTimeMillis());
        String val = getActivity().getSharedPreferences(Constants.SP_NAME, 0).getString(Constants.REMIND_TIME, "未设置");
        mText.setText(val);
        mWheelViewHH.setAdapter(new AbNumericWheelAdapter(0, 23));
        mWheelViewHH.setCyclic(true);
        mWheelViewHH.setLabel("点");
        mWheelViewHH.setCurrentItem(defaultHour);
        mWheelViewHH.setValueTextSize(35);
        mWheelViewHH.setLabelTextSize(35);
        mWheelViewHH.setLabelTextColor(-2147483648);
        mWheelViewMM.setAdapter(new AbNumericWheelAdapter(0, 59));
        mWheelViewMM.setCyclic(true);
        mWheelViewMM.setLabel("分");
        mWheelViewMM.setCurrentItem(defaultMinute);
        mWheelViewMM.setValueTextSize(35);
        mWheelViewMM.setLabelTextSize(35);
        mWheelViewMM.setLabelTextColor(-2147483648);
        okBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                AbDialogUtil.removeDialog(v.getContext());
                int index2 = mWheelViewHH.getCurrentItem();
                int index3 = mWheelViewMM.getCurrentItem();
                Log.i(TAG, "index2=" + index2);
                Log.i(TAG, "index3=" + index3);
                String val = AbStrUtil.dateTimeFormat(index2 + ":" + index3);
                Log.i(TAG, "val=" + val);
                mText.setText(val);

                //保存設置时间
                getActivity().getSharedPreferences(Constants.SP_NAME, 0).edit().putString(Constants.REMIND_TIME, val).commit();
                callback.notifyReloadFragment();

                Toast.makeText(getActivity(), "您设置的提醒时间为:" + val, Toast.LENGTH_SHORT).show();

//                c.setTimeInMillis(System.currentTimeMillis());
//                c.set(Calendar.HOUR_OF_DAY, index2);
//                c.set(Calendar.MINUTE, index3);
//                c.set(Calendar.SECOND, 0);
//                c.set(Calendar.MILLISECOND, 0);

                Date dt = new Date();
                Log.i(TAG,"new Date() = "+dt.toString());
                dt.setHours(index2);
                dt.setMinutes(index3);
                long date = dt.getTime();
                Log.i(TAG,"date == "+date +"  current time = "+System.currentTimeMillis());
                if (date < System.currentTimeMillis()) {
                    //Log.i(TAG,"date.getdate="+dt.getDate());
                    dt.setDate(dt.getDate()+1);
                    //Log.i(TAG,"date.getdate="+dt.getDate());
                    //Log.i(TAG,"date == "+date +"  current time = "+System.currentTimeMillis());
                    date = dt.getTime();
                }



                Intent intent = new Intent(getActivity(), RingAlarm.class);
                PendingIntent sender = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);


                //am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), sender);
                F1Application.getAlarmManager().setRepeating(AlarmManager.RTC_WAKEUP, date, 1 * 60 * 1000 * 60 * 24, sender);
            }
        });
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                AbDialogUtil.removeDialog(v.getContext());
                callback.notifyReloadFragment();
            }
        });
    }

    @Override
    public void onPause() {
        Log.i(TAG, "onPause()");
        super.onPause();

    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_time:
                if (!dialogShowing) {
                    //第一个参数是弹出的布局，第二个参数是显示的位置
                    AbDialogUtil.showDialog(mTimeView3, Gravity.BOTTOM);
                    dialogShowing = true;
                } else {
                    dialogShowing = false;
                    callback.notifyReloadFragment();
                }
                //c.setTimeInMillis(System.currentTimeMillis());
                break;

            case R.id.tv_clean:
                //清除缓存
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("确定清除缓存吗？");
                builder.setNegativeButton("取消", null);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });

                builder.show();
                break;
            case R.id.tv_about:
                //跳转到关于页面
                Intent intent = new Intent(getActivity(), AboutActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_update:
                if (!NetUtil.isNetOK(getActivity())) {
                    MessageUtil.showToast(getActivity(), "无网络访问");
                    return;
                }
                if (HttpCookies.getSessionId() == null || HttpCookies.getSessionId().equals("")) {
                    Log.i(TAG, "未登陆，在线验证");
                    MessageUtil.showLoginValidataPop(getActivity().getApplicationContext(), tv_update, 1, SettingFragment.this);
                }
                checkPudate();
                break;
        }
    }


    private void checkPudate() {
        MessageUtil.showProgressDialog(getActivity(), "正在检查更新");
        new getNewestAPKInfoTask().execute();
    }


    private class getNewestAPKInfoTask extends AsyncTask<Void, Void, String> {
        @Override
        protected String doInBackground(Void... params) {
            String url = AppConfig.BASE_URL + Constants.APK_UPDATE_URL;
            Log.i(TAG, "获取版本信息URL：" + url);
            String result = new HttpClient(getActivity()).doGet(url);
            Log.i(TAG, "获取版本信息结果：" + result);
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            gson = new Gson();
            try {
                apkModel = gson.fromJson(s, new TypeToken<APKModel>() {
                }.getType());
                MessageUtil.dismissProgressDialog();
                if (apkModel == null) {
                    MessageUtil.showToast(getActivity(), "获取版本信息失败！");
                    return;
                }
                if (apkModel.code == 0) {
                    if (AppConfig.VERSION_CODE == apkModel.version_code) {
                        MessageUtil.showToast(getActivity(), "已是最新版本！");
                    } else {
                        MessageUtil.showPopDialog(getActivity(), tv_update, "更新", "有新版本，是否更新", "确定", 0, SettingFragment.this);
                    }
                } else {
                    MessageUtil.showToast(getActivity(), "获取版本信息失败！");
                }
            } catch (Exception e) {
                MessageUtil.showToast(getActivity(), "获取版本信息失败！");
            }
        }

    }

    class DownLoadFile extends AsyncTask<String, Integer, String> {
        /* 后台线程 */
        @Override
        protected String doInBackground(String... params) {
            try {
                String url = AppConfig.BASE_URL + Constants.DOWN_APK_URL;
                Log.i(TAG, "下载APK地址" + url);
                DefaultHttpClient client = new DefaultHttpClient();
                HttpGet httpRequest = new HttpGet(url);
                httpRequest.setHeader("Accept-Encoding", "gzip");// 设置压缩格式
                HttpCookies li = new HttpCookies(getActivity());
                CookieStore cs = li.getuCookie();
                if (cs != null) {
                    client.setCookieStore(li.getuCookie());
                }
                HttpResponse httpResponse = client.execute(httpRequest);
                int resCode = httpResponse.getStatusLine().getStatusCode();
                Log.i(TAG, "下载apk返回code：" + resCode);

                if (resCode == 601) {
                    MessageUtil.showToast(getActivity(), "网络异常，请重试");
                }

                if (resCode == 200) {
                    HttpEntity entity = httpResponse.getEntity();
                    int length = 0;
                    InputStream in = entity.getContent();
                    String path = AppConfig.DB_FILE_PATh;
                    File file = new File(path);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    FileOutputStream out = new FileOutputStream(new File(AppConfig.DB_FILE_PATh + "/repair.apk"));
                    byte[] buff = new byte[1024 * 1024 * 4];
                    Log.i(TAG, "总下载量" + apkModel.size);
                    while ((length = in.read(buff)) > 0) {
                        currentFileSize += (length);
                        int str1 = (int) (currentFileSize * 100 / apkModel.size);
                        if (str1 - persent == 1) {
                            persent = str1;
                            publishProgress(str1);
                        }
                        out.write(buff, 0, length);
                    }
                    in.close();
                    out.flush();
                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }


        /* 预处理UI线程 */
        @Override
        protected void onPreExecute() {
            currentFileSize = 0;
            super.onPreExecute();
        }

        /* 结束时的UI线程 */
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            MessageUtil.dismissProgressDialog();
            File f = new File(AppConfig.DB_FILE_PATh + "/repair.apk");
            if (f.exists() && f.length() > 1024 * 1024) {
                MessageUtil.showToast(getActivity(), "下载完成");
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(f),
                        "application/vnd.android.package-archive");

                getActivity().startActivity(intent);

            } else {
                MessageUtil.showToast(getActivity(), "下载失败");
            }
        }

        /* 处理UI线程，会被多次调用,触发事件为publicProgress方法 */
        @Override
        protected void onProgressUpdate(Integer... values) {
            //   pdialog.setProgress(values[0]);
        }
    }

    private class LoginTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            String url = AppConfig.BASE_URL + Constants.LOGIN_URL;
            Log.i(TAG, "登陆url：" + url);
            String result = "";
            Map<String, String> map = new HashMap<>();
            map.put("username", params[0]);
            map.put("password", params[1]);
            map.put("pageStyle", "");
            map.put("logined", params[0]);
            map.put("agent", "1");
            result = new HttpClient(getActivity().getApplicationContext()).doPost(url, map);
            Log.i(TAG, "登陆返回结果：" + result);
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Gson gson = new Gson();
            try {
                User4Json uj = gson.fromJson(s, new TypeToken<User4Json>() {
                }.getType());
                if (uj.successful.equals("true")) {
                    MessageUtil.showToast(getActivity().getApplicationContext(), "验证成功");
                } else {
                    MessageUtil.showToast(getActivity(), uj.resultHint);
                    HttpCookies.setSessionId(null);
                }
            } catch (Exception e) {
                MessageUtil.showToast(getActivity(), "验证失败");
            }
        }
    }

    public interface NotifyParentActivity {
        public void notifyReloadFragment();
    }
}